<template>
  <el-dialog
    v-model="dialogVisible"
    draggable
    :close-on-click-modal="false"
    title="字典管理"
    width="680px"
    center
  >
    <el-form
      ref="formRef"
      :model="formValue"
      :rules="rules"
      label-width="80px"
      class="demo-ruleForm"
      status-icon
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="字典名称" prop="name">
            <el-input v-model="formValue.name" placeholder="字典名称"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="字典键" prop="code">
            <el-input
              v-model="formValue.code"
              placeholder="字典键"
              :disabled="method === 'edit'"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="字典值" prop="value">
            <el-input v-model="formValue.value" type="text" placeholder="字典值">
              <template #append>
                <el-button icon="Picture" @click="upload" />
              </template>
            </el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12"
          ><el-form-item label="上级字典" prop="parentCode">
            <el-tree-select
              style="width: 100%"
              v-model="formValue.parentCode"
              :data="treeList"
              :render-after-expand="false"
              placeholder="上级字典"
              clearable
              check-strictly="true"
            >
            </el-tree-select> </el-form-item
        ></el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="sort">
            <el-input v-model="formValue.sort" placeholder="排序"></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="描述" prop="description">
            <el-input
              v-model="formValue.description"
              type="textarea"
              :rows="3"
              placeholder="描述"
            ></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="状态" prop="enable">
            <el-switch
              v-model="formValue.enable"
              style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
              inline-prompt
              active-text="启用"
              inactive-text="停用"
            ></el-switch>
          </el-form-item>
        </el-col>
      </el-row>

      <div style="text-align: center" v-has="['sysdict:add', 'sysdict:edit']">
        <el-button type="primary" auto-insert-space @click="submit(formRef)"> 保存 </el-button>
        <el-button @click="reset" auto-insert-space>重置</el-button>
      </div>
      <ImgUploadDialog ref="uploadDialog" @upload-success="setImgUrl"></ImgUploadDialog>
    </el-form>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref, onActivated } from 'vue'
import type { FormInstance, FormRules, ElMessage, ElMessageBox } from 'element-plus'
import {
  sysdictgetById,
  sysdictSave,
  sysdictUpdateById,
  getSysDictListTree
} from '@/apis/sysdict.js'
let uploadDialog = ref()
interface RuleForm {
  name: string
  code: string
  value: string
  parentCode: string
  sort: number
  description: string
  enable: boolean
}

const formRef = ref()

let formValue = ref<RuleForm>({
  name: '',
  code: '',
  value: '',
  parentCode: '',
  sort: 100,
  description: '',
  enable: true
})

/**
 * code 唯一校验
 */
const validateCode = (rule: any, value: any, callback: any) => {
  const reg = /^[0-9a-zA-Z_]{4,16}$/
  if (!reg.test(value)) {
    callback(new Error('4~16位由字母、数字、下划线组成'))
  } else {
    //新增操作再去判断 code 是否唯一
    if (method.value === 'add') {
      sysdictgetById({ code: value })
        .then(function (response) {
          if (response != null) {
            callback(new Error('字典键已存在'))
          } else {
            callback()
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    } else {
      callback()
    }
  }
}

/**
 * 排序 数字校验
 */
const validateSort = (rule: any, value: any, callback: any) => {
  const reg = /^\d{1,4}$/
  if (!reg.test(value)) {
    callback(new Error('顺序必须是数值,最小值1，最大值9999'))
  } else {
    callback()
  }
}

let rules = reactive<FormRules>({
  code: [{ required: true, message: '请输入字典键', trigger: 'blur' }, { validator: validateCode }],
  name: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
  sort: [{ required: true, message: '请输入排序', trigger: 'blur' }, { validator: validateSort }]
})

const emit = defineEmits(['getPage'])

let dialogVisible = ref(false)
let method = ref('')

const options = Array.from({ length: 10 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`
}))

let originValue = {}
function open(code, m) {
  getListTree()

  //新增还是修改
  method.value = m

  dialogVisible.value = true

  if (code != undefined && code != null) {
    sysdictgetById({
      code
    })
      .then(function (response) {
        formValue.value = response
        originValue = JSON.parse(JSON.stringify(response))
      })
      .catch(function (error) {
        console.log(error)
      })
  } else {
    let v = {
      name: '',
      code: '',
      value: '',
      parentCode: '',
      sort: 100,
      description: '',
      enable: true
    }

    formValue.value = v

    originValue = JSON.parse(JSON.stringify(v))
  }

  reset()
}

function baoCun() {
  ElMessageBox.confirm('确定要保存吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      if (method.value === 'add') {
        sysdictSave(formValue.value)
          .then(function (response) {
            if (response) {
              ElMessage({
                type: 'success',
                message: '保存成功'
              })

              dialogVisible.value = false

              emit('getPage')
            }
          })
          .catch(function (error) {
            console.log(error)
          })
      } else if (method.value === 'edit') {
        sysdictUpdateById(formValue.value)
          .then(function (response) {
            if (response) {
              ElMessage({
                type: 'success',
                message: '保存成功'
              })

              dialogVisible.value = false
              emit('getPage')
            }
          })
          .catch(function (error) {
            console.log(error)
          })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消保存'
      })
    })
}

function setImgUrl(url) {
  formValue.value.value = url
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      baoCun()
    } else {
      console.log('error submit!', fields)
    }
  })
}

function reset() {
  if (!formRef) return
  formRef.value.resetFields()
  formValue.value = JSON.parse(JSON.stringify(originValue))
}

let treeList = reactive([])

function getListTree() {
  treeList = reactive([])
  getSysDictListTree()
    .then((response) => {
      response.forEach((element) => {
        let obj = {
          value: element.id,
          label: element.name,
          children: []
        }
        if (element.children != undefined && element.children.length > 0) {
          element.children.forEach((children) => {
            obj.children.push({
              value: children.id,
              label: children.name
            })
          })
        }
        treeList.push(obj)
      })
    })
    .catch((error) => {
      console.log(error)
    })
}

onActivated(() => {
  // getListTree()
})

function upload() {
  uploadDialog.value.open(formValue.value.value)
}
function preview() {}

defineExpose({ open })
</script>

<style scoped></style>
